﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aspose.Cells.Rendering;
using System.Drawing.Imaging;
using Aspose.Cells;
using System.IO;

namespace Meeting.Office2Image
{
    /// <summary>
    /// Excel转换图片
    /// </summary>
    public class Excel2Image
    {
        public static string errorString = "";

        /// <summary>
        /// 把Excel 转换成图片目前只支持第一张表，没有支持多sheet处理，要进行多sheet处理可以再加一层循环
        /// </summary>
        /// <param name="inputPath"></param>
        /// <param name="outputPath"></param>
        /// <param name="imageName"></param>
        /// <param name="startPageNum"></param>
        /// <param name="endPageNum"></param>
        /// <param name="imageFormat"></param>
        /// <param name="imageCount"></param>
        /// <returns></returns>
        public static bool ConvertExcelToImage(string inputPath, string outputPath, string imageName,
                            int startPageNum, int endPageNum, ImageFormat imageFormat, out int imageCount)
        {

            imageCount = 0;
            try
            {
                //XLSConvertToPDF(inputPath, Path.Combine(outputPath, imageName) + (imageName.Length == 0 ? "" : "_") + "1.pdf");
                Workbook book = new Workbook(inputPath);
                //book.Save(Path.Combine(outputPath, imageName) + (imageName.Length == 0 ? "" : "_") + "1.pdf", SaveFormat.Pdf);
                //imageCount = 1;
                //book.Worksheets.Count
                Aspose.Cells.Worksheet sheet = book.Worksheets[0];
                
                sheet.PageSetup.Zoom = 70;
                sheet.PageSetup.LeftMargin = 1;
                sheet.PageSetup.RightMargin = 0;
                sheet.PageSetup.TopMargin = 1;
                sheet.PageSetup.BottomMargin = 0;

                ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
                imgOptions.ImageFormat = ImageFormat.Jpeg;
                imgOptions.PrintingPage = PrintingPageType.Default;
                imgOptions.IsCellAutoFit = false;
                imgOptions.IsImageFitToPage = false;
                imgOptions.HorizontalResolution = 150;
                imgOptions.VerticalResolution = 150;
                SheetRender sr = new SheetRender(sheet, imgOptions);
                if (startPageNum < 0) startPageNum = 0;
                if (startPageNum > sr.PageCount) throw new Exception("起始页超出范围");

                if (endPageNum < startPageNum) throw new Exception("结束页小于于起始页");
                if (endPageNum > sr.PageCount || endPageNum <= 0) endPageNum = sr.PageCount;
                int iCount = 0;

                for (int j = startPageNum; j < endPageNum; j++)
                {
                    iCount++;

                    sr.ToImage(j, Path.Combine(outputPath, imageName) + (imageName.Length == 0 ? "" : "_") + (j + 1).ToString() + "." + imageFormat.ToString());
                }
                imageCount = iCount;
                
                return true;
            }
            catch (Exception ex)
            {
                errorString = ex.Message;
                return false;
            }
        }


        /// <summary>
        /// 把Excel文件转换成PDF格式文件
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true=转换成功</returns>
        public static bool XLSConvertToPDF(string sourcePath, string targetPath)
        {
            bool result = false;
            Microsoft.Office.Interop.Excel.XlFixedFormatType targetType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF;
            object missing = Type.Missing;
            Microsoft.Office.Interop.Excel.ApplicationClass application = null;
            Microsoft.Office.Interop.Excel.Workbook workBook = null;
            try
            {
                application = new Microsoft.Office.Interop.Excel.ApplicationClass();
                object target = targetPath;
                object type = targetType;
                workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
                        missing, missing, missing, missing, missing, missing, missing, missing, missing);
                workBook.ExportAsFixedFormat(targetType, target, Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }
    }
}
